package com.hl.vcd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hl.common.utils.OssUtils;
import com.hl.vcd.entity.User;
import com.hl.vcd.mapper.UserMapper;
import com.hl.vcd.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 朱炫达
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public void addUser(User user) {
        baseMapper.insert(user);
    }

    @Override
    public User getUserByMail(String mail) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mail",mail);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public User getUserById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public User selectUserByMailAndPassword(String mail, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mail",mail);
        wrapper.eq("password",password);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void updateUser(User user) {
        baseMapper.updateById(user);
    }

    @Override
    public boolean uploadUserAvatarById(MultipartFile avatarFile, String id) {
        String avatarUrl = null;
        try {
            if (ObjectUtils.isEmpty(avatarFile) || avatarFile.getSize() <= 0) {
                throw new Exception("上传文件大小为空");
            }
            avatarUrl = OssUtils.uploadFile(avatarFile,OssUtils.typeAvatar);
            User updateUser = new User();
            updateUser.setId(id).setAvatarUrl(avatarUrl);
            baseMapper.updateById(updateUser);

        }catch (Exception e){
            e.printStackTrace();
            if (avatarUrl != null){
                OssUtils.deleteFile(avatarUrl);
            }
            return false;
        }
        return true;
    }
}
